#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>

#include "./../../inc/homepage.h"
#include "./../../inc/msg_popup.h"
#include "./../../inc/cJSON.h"
#include "./../../inc/user_event.h"
#include "./../../inc/tcp.h"

#define ULGRAY 0xF5F5F5
#define LDWHITE 0xF6F6F6
// #define LDWHITE 0xFDFDFD

lv_obj_t * new_friend_list_card          = NULL;                      // 朋友申请卡片
FriendApplyList_t g_friend_apply_cache   = {0};                       // 缓存的好友申请数据
pthread_mutex_t g_cache_mutex            = PTHREAD_MUTEX_INITIALIZER; // 保护缓存的互斥锁
bool g_has_new_data                      = false;                     // 是否有新数据
static lv_obj_t * g_friend_apply_overlay = NULL;                      // 半透明背景层（顶层）

static void close_friend_apply_list_event(lv_event_t * e);
static void on_accept_click(lv_event_t * e);
static void on_reject_click(lv_event_t * e);
static void render_friend_list_from_cache(lv_obj_t * parent, const FriendApplyList_t * cache);
static char * pack_friend_apply_json(int apply_id, const char * action);
static void remove_cache_item_by_apply_id(int apply_id);

/**
 * 创建/显示好友申请页面，同时读取全局缓存g_friend_apply_cache渲染列表
 * @param parent 父容器（通常是当前屏幕 lv_scr_act()）
 */
void show_friend_apply_list()
{
    // 加锁：避免创建UI时，线程同时修改缓存
    pthread_mutex_lock(&g_cache_mutex);

    if(g_friend_apply_overlay == NULL) {
        // 创建半透明背景层（overlay）
        g_friend_apply_overlay = lv_obj_create(lv_scr_act());
        lv_obj_set_size(g_friend_apply_overlay, LV_HOR_RES, LV_VER_RES);
        lv_obj_set_style_bg_color(g_friend_apply_overlay, lv_color_black(), 0);
        lv_obj_set_style_bg_opa(g_friend_apply_overlay, LV_OPA_50, 0);
        lv_obj_set_style_border_width(g_friend_apply_overlay, 0, 0);
        lv_obj_set_style_radius(g_friend_apply_overlay, 0, 0);
        lv_obj_center(g_friend_apply_overlay);
        lv_obj_clear_flag(g_friend_apply_overlay, LV_OBJ_FLAG_SCROLLABLE);

        // 创建白色列表卡片（friend_apply_list）
        lv_obj_t * friend_apply_list = lv_obj_create(g_friend_apply_overlay);
        lv_obj_set_size(friend_apply_list, 300, 400);
        lv_obj_set_style_radius(friend_apply_list, 20, 0);
        lv_obj_set_style_bg_color(friend_apply_list, lv_color_white(), 0);
        lv_obj_set_style_bg_opa(friend_apply_list, LV_OPA_100, 0);
        lv_obj_set_style_border_width(friend_apply_list, 0, 0);
        lv_obj_set_style_pad_all(friend_apply_list, 0, 0);
        lv_obj_set_style_border_color(friend_apply_list, lv_color_hex(0xE0E0E0), 0);
        lv_obj_set_style_shadow_width(friend_apply_list, 20, 0);
        lv_obj_set_style_shadow_opa(friend_apply_list, LV_OPA_30, 0);
        lv_obj_clear_flag(friend_apply_list, LV_OBJ_FLAG_SCROLLABLE);
        lv_obj_center(friend_apply_list);

        //  创建标题栏（title_card）
        lv_obj_t * title_card = lv_obj_create(friend_apply_list);
        lv_obj_set_size(title_card, LV_PCT(100), LV_PCT(15));
        lv_obj_set_style_radius(title_card, 20, 0); // 顶部圆角与卡片一致
        lv_obj_set_style_bg_color(title_card, lv_color_white(), 0);
        lv_obj_set_style_bg_opa(title_card, LV_OPA_100, 0);
        lv_obj_set_style_border_width(title_card, 0, 0);
        lv_obj_set_style_pad_all(title_card, 0, 0);

        // 标题文本
        lv_obj_t * title = lv_label_create(title_card);
        lv_label_set_text(title, "新的朋友");
        lv_obj_set_style_text_font(title, &SourceHanSansCN_Bold_20, LV_PART_MAIN | LV_STATE_DEFAULT);
        lv_obj_set_style_text_color(title, lv_color_hex(0x333333), 0);
        lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 15);
        lv_obj_clear_flag(title, LV_OBJ_FLAG_SCROLLABLE);

        //  标题下划线
        lv_obj_t * title_underline = lv_obj_create(title_card);
        lv_obj_align(title_underline, LV_ALIGN_BOTTOM_MID, 0, -1);
        lv_obj_set_size(title_underline, LV_PCT(90), 1);
        lv_obj_set_style_bg_color(title_underline, lv_color_hex(ULGRAY), 0);
        lv_obj_set_style_radius(title_underline, 0, 0);
        lv_obj_set_style_border_width(title_underline, 0, 0);

        //  创建好友列表容器（new_friend_list_card，用于渲染数据）
        new_friend_list_card = lv_list_create(friend_apply_list);
        lv_obj_set_size(new_friend_list_card, LV_PCT(90), LV_PCT(85));
        lv_obj_align(new_friend_list_card, LV_ALIGN_BOTTOM_MID, 0, -5);
        lv_obj_set_style_bg_color(new_friend_list_card, lv_color_white(), 0);
        lv_obj_set_style_bg_opa(new_friend_list_card, LV_OPA_100, 0);
        lv_obj_set_style_border_width(new_friend_list_card, 0, 0);
        lv_obj_set_style_pad_all(new_friend_list_card, 0, 0);

        //  绑定关闭事件（点击背景层关闭页面）
        lv_obj_add_event_cb(g_friend_apply_overlay, close_friend_apply_list_event, LV_EVENT_CLICKED, NULL);
    } else {
        lv_obj_clear_flag(g_friend_apply_overlay, LV_OBJ_FLAG_HIDDEN);
    }

    // 读取全局缓存，渲染好友列表
    if(new_friend_list_card != NULL && lv_obj_is_valid(new_friend_list_card)) {
        if(g_has_new_data && g_friend_apply_cache.count > 0 && g_friend_apply_cache.items != NULL) {
            // 缓存有数据：渲染列表
            render_friend_list_from_cache(new_friend_list_card, &g_friend_apply_cache);
        } else {
            // 缓存无数据：显示“暂无申请”
            lv_obj_clean(new_friend_list_card);
            lv_obj_t * empty_label = lv_label_create(new_friend_list_card);
            lv_label_set_text(empty_label, "暂无新的好友申请");
            lv_obj_align(empty_label, LV_ALIGN_CENTER, 0, 0);
            lv_obj_set_style_text_font(empty_label, &SourceHanSansCN_Bold_20, 0);
        }
    }

    // 解锁
    pthread_mutex_unlock(&g_cache_mutex);
}

static void close_friend_apply_list_event(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if(code == LV_EVENT_CLICKED) {
        printf("close friend apply list\n");
        if(g_friend_apply_overlay != NULL && lv_obj_is_valid(g_friend_apply_overlay)) {
            lv_obj_add_flag(g_friend_apply_overlay, LV_OBJ_FLAG_HIDDEN);
        }
        printf("close friend apply list end\n");
    }
}

// 同意按钮回调
static void on_accept_click(lv_event_t * e)
{
    pthread_mutex_lock(&g_cache_mutex);

    // 1. 获取绑定的索引（不再绑定指针）
    lv_obj_t * btn = lv_event_get_target(e);
    int index      = (int)(intptr_t)lv_obj_get_user_data(btn); // 索引转换

    // 2. 验证索引有效性
    if(index < 0 || index >= g_friend_apply_cache.count || g_friend_apply_cache.items == NULL) {
        printf("on_accept_click: 索引无效（%d）\n", index);
        pthread_mutex_unlock(&g_cache_mutex);
        return;
    }

    // 3. 通过索引访问缓存项（安全可靠）
    FriendApplyItem_t * item = &g_friend_apply_cache.items[index];
    int apply_id             = item->apply_id;
    const char * friend_name = item->from_name;
    printf("同意添加好友：ID=%d，名称=%s\n", apply_id, friend_name);

    // 4. 解锁后发送消息
    pthread_mutex_unlock(&g_cache_mutex);
    char * json_str = pack_friend_apply_json(apply_id, "agree");
    if(json_str != NULL) {
        send_message_to_server(&server_info, json_str);
        free(json_str);
    }

    // 5. 处理UI和缓存
    pthread_mutex_lock(&g_cache_mutex);
    lv_obj_t * item_card = lv_obj_get_parent(btn);
    if(lv_obj_is_valid(item_card)) {
        lv_obj_del(item_card);
    }
    remove_cache_item_by_apply_id(apply_id);

    if(g_friend_apply_cache.count == 0 && lv_obj_is_valid(new_friend_list_card)) {
        lv_obj_clean(new_friend_list_card);
        lv_obj_t * empty_label = lv_label_create(new_friend_list_card);
        lv_label_set_text(empty_label, "暂无新的好友申请");
        lv_obj_align(empty_label, LV_ALIGN_CENTER, 0, 0);
    }
    pthread_mutex_unlock(&g_cache_mutex);
}

// 拒绝按钮回调
static void on_reject_click(lv_event_t * e)
{
    pthread_mutex_lock(&g_cache_mutex);

    // 1. 获取绑定的索引
    lv_obj_t * btn = lv_event_get_target(e);
    int index      = (int)(intptr_t)lv_obj_get_user_data(btn);

    // 2. 验证索引有效性
    if(index < 0 || index >= g_friend_apply_cache.count || g_friend_apply_cache.items == NULL) {
        printf("on_reject_click: 索引无效（%d）\n", index);
        pthread_mutex_unlock(&g_cache_mutex);
        return;
    }

    // 3. 通过索引访问缓存项
    FriendApplyItem_t * item = &g_friend_apply_cache.items[index];
    int apply_id             = item->apply_id;
    printf("拒绝添加好友：ID=%d，名称=%s\n", apply_id, item->from_name);

    // 4. 解锁后发送消息
    pthread_mutex_unlock(&g_cache_mutex);
    char * json_str = pack_friend_apply_json(apply_id, "refuse");
    if(json_str != NULL) {
        send_message_to_server(&server_info, json_str);
        free(json_str);
    }

    // 5. 处理UI和缓存
    pthread_mutex_lock(&g_cache_mutex);
    lv_obj_t * item_card = lv_obj_get_parent(btn);
    if(lv_obj_is_valid(item_card)) {
        lv_obj_del(item_card);
    }
    remove_cache_item_by_apply_id(apply_id);

    if(g_friend_apply_cache.count == 0 && lv_obj_is_valid(new_friend_list_card)) {
        lv_obj_clean(new_friend_list_card);
        lv_obj_t * empty_label = lv_label_create(new_friend_list_card);
        lv_label_set_text(empty_label, "暂无新的好友申请");
        lv_obj_align(empty_label, LV_ALIGN_CENTER, 0, 0);
    }
    pthread_mutex_unlock(&g_cache_mutex);
}

/**
 * 从全局缓存渲染好友申请列表
 */
static void render_friend_list_from_cache(lv_obj_t * parent, const FriendApplyList_t * cache)
{
    if(parent == NULL || cache == NULL) return;

    // 清空旧列表
    lv_obj_clean(parent);
    // 重置列表项高度累计
    int total_item_height = 0;

    // 遍历缓存，创建每个列表项
    for(int i = 0; i < cache->count; i++) {
        const FriendApplyItem_t * item = &cache->items[i];

        // 创建列表项卡片（固定高度60px）
        lv_obj_t * item_card = lv_obj_create(parent);
        lv_obj_set_size(item_card, LV_PCT(100), 60);
        lv_obj_set_y(item_card, total_item_height);
        lv_obj_set_style_bg_color(item_card, lv_color_white(), 0);
        lv_obj_set_style_bg_opa(item_card, LV_OPA_100, 0);
        lv_obj_set_style_border_width(item_card, 0, 0);
        lv_obj_set_style_pad_all(item_card, 0, 0);
        lv_obj_clear_flag(item_card, LV_OBJ_FLAG_SCROLLABLE);

        // 显示申请人名称
        lv_obj_t * name_label = lv_label_create(item_card);
        lv_label_set_text(name_label, item->from_name);
        lv_obj_align(name_label, LV_ALIGN_LEFT_MID, 10, 0);
        lv_obj_set_style_text_color(name_label, lv_color_hex(0x333333), 0);
        lv_obj_set_style_text_font(name_label, &SourceHanSansCN_Bold_20, 0);
        lv_obj_clear_flag(name_label, LV_OBJ_FLAG_SCROLLABLE);

        // 同意按钮：绑定当前索引（而非指针）
        lv_obj_t * accept_btn = lv_btn_create(item_card);
        lv_obj_set_size(accept_btn, 80, 35);
        lv_obj_align(accept_btn, LV_ALIGN_RIGHT_MID, -100, 0);
        lv_obj_set_style_bg_color(accept_btn, lv_color_hex(0x4CAF50), 0);
        lv_obj_set_style_bg_opa(accept_btn, LV_OPA_100, 0);
        lv_obj_set_style_radius(accept_btn, 5, 0);
        lv_obj_set_style_border_width(accept_btn, 0, 0);
        lv_obj_clear_flag(accept_btn, LV_OBJ_FLAG_SCROLLABLE);

        lv_obj_t * accept_label = lv_label_create(accept_btn);
        lv_label_set_text(accept_label, "同意");
        lv_obj_center(accept_label);
        lv_obj_set_style_text_color(accept_label, lv_color_white(), 0);
        lv_obj_set_style_text_font(accept_label, &SourceHanSansCN_Bold_20, 0);
        lv_obj_clear_flag(accept_label, LV_OBJ_FLAG_SCROLLABLE);

        // 核心：绑定索引值（通过intptr_t安全转换）
        lv_obj_set_user_data(accept_btn, (void *)(intptr_t)i);
        lv_obj_add_event_cb(accept_btn, on_accept_click, LV_EVENT_CLICKED, NULL);

        // 拒绝按钮：绑定当前索引
        lv_obj_t * reject_btn = lv_btn_create(item_card);
        lv_obj_set_size(reject_btn, 80, 35);
        lv_obj_align(reject_btn, LV_ALIGN_RIGHT_MID, -10, 0);
        lv_obj_set_style_bg_color(reject_btn, lv_color_hex(0xF44336), 0);
        lv_obj_set_style_bg_opa(reject_btn, LV_OPA_100, 0);
        lv_obj_set_style_radius(reject_btn, 5, 0);
        lv_obj_set_style_border_width(reject_btn, 0, 0);
        lv_obj_clear_flag(reject_btn, LV_OBJ_FLAG_SCROLLABLE);

        lv_obj_t * reject_label = lv_label_create(reject_btn);
        lv_label_set_text(reject_label, "拒绝");
        lv_obj_center(reject_label);
        lv_obj_set_style_text_color(reject_label, lv_color_white(), 0);
        lv_obj_set_style_text_font(reject_label, &SourceHanSansCN_Bold_20, 0);
        lv_obj_clear_flag(reject_label, LV_OBJ_FLAG_SCROLLABLE);

        // 核心：绑定索引值
        lv_obj_set_user_data(reject_btn, (void *)(intptr_t)i);
        lv_obj_add_event_cb(reject_btn, on_reject_click, LV_EVENT_CLICKED, NULL);

        // 更新下一个item的Y坐标
        total_item_height += lv_obj_get_height(item_card);
    }
}

// 解析好友申请JSON数据
void parse_friend_apply_json(const char * json_str, FriendApplyList_t * applyList)
{
    applyList->count = 0;
    applyList->items = NULL;

    if(json_str == NULL || applyList == NULL) {
        return;
    }

    cJSON * root = cJSON_Parse(json_str);
    if(root == NULL) {
        printf("JSON解析失败\n");
        return;
    }

    cJSON * payload = cJSON_GetObjectItem(root, "payload");
    if(payload != NULL) {
        cJSON * count_item = cJSON_GetObjectItem(payload, "count");
        if(count_item != NULL && cJSON_IsNumber(count_item)) {
            applyList->count = count_item->valueint;
        }

        if(applyList->count > 0) {
            applyList->items = (FriendApplyItem_t *)malloc(sizeof(FriendApplyItem_t) * applyList->count);
            if(applyList->items != NULL) {
                cJSON * items = cJSON_GetObjectItem(payload, "items");
                cJSON * item  = NULL;
                int i         = 0;

                cJSON_ArrayForEach(item, items)
                {
                    if(i < applyList->count) {
                        // 解析apply_id
                        cJSON * id_item = cJSON_GetObjectItem(item, "apply_id");
                        if(id_item != NULL && cJSON_IsNumber(id_item)) {
                            applyList->items[i].apply_id = id_item->valueint;
                        }

                        // 解析from_userid
                        cJSON * userid_item = cJSON_GetObjectItem(item, "from_userid");
                        if(userid_item != NULL && cJSON_IsString(userid_item) && userid_item->valuestring != NULL) {
                            strncpy(applyList->items[i].from_userid, userid_item->valuestring,
                                    sizeof(applyList->items[i].from_userid) - 1);
                        }

                        // 解析from_name
                        cJSON * name_item = cJSON_GetObjectItem(item, "from_name");
                        if(name_item != NULL && cJSON_IsString(name_item) && name_item->valuestring != NULL) {
                            strncpy(applyList->items[i].from_name, name_item->valuestring,
                                    sizeof(applyList->items[i].from_name) - 1);
                        }

                        // 解析apply_msg
                        cJSON * msg_item = cJSON_GetObjectItem(item, "apply_msg");
                        if(msg_item != NULL && cJSON_IsString(msg_item) && msg_item->valuestring != NULL) {
                            strncpy(applyList->items[i].apply_msg, msg_item->valuestring,
                                    sizeof(applyList->items[i].apply_msg) - 1);
                        }

                        // 解析create_time
                        cJSON * time_item = cJSON_GetObjectItem(item, "create_time");
                        if(time_item != NULL && cJSON_IsString(time_item) && time_item->valuestring != NULL) {
                            strncpy(applyList->items[i].create_time, time_item->valuestring,
                                    sizeof(applyList->items[i].create_time) - 1);
                        }

                        i++;
                    }
                }
            }
        }
    }

    cJSON_Delete(root);
}

// 将解析后的好友申请数据保存到全局缓存
void save_friend_apply_to_cache(FriendApplyList_t * new_list)
{
    if(new_list == NULL) return;

    pthread_mutex_lock(&g_cache_mutex);

    // 清除旧缓存数据
    if(g_friend_apply_cache.items != NULL) {
        free(g_friend_apply_cache.items);
        g_friend_apply_cache.items = NULL;
    }
    g_friend_apply_cache.count = 0;
    g_has_new_data             = false;

    // 保存新数据到缓存
    if(new_list->count > 0 && new_list->items != NULL) {
        g_friend_apply_cache.items = (FriendApplyItem_t *)malloc(sizeof(FriendApplyItem_t) * new_list->count);
        if(g_friend_apply_cache.items != NULL) {
            memcpy(g_friend_apply_cache.items, new_list->items, sizeof(FriendApplyItem_t) * new_list->count);
            g_friend_apply_cache.count = new_list->count;
            g_has_new_data             = true;
        }
    }

    pthread_mutex_unlock(&g_cache_mutex);
}

// 打包好友申请操作的JSON（agree/refuse）
static char * pack_friend_apply_json(int apply_id, const char * action)
{
    if(action == NULL || (strcmp(action, "agree") != 0 && strcmp(action, "refuse") != 0)) {
        printf("pack_friend_apply_json: 无效的操作类型\n");
        return NULL;
    }

    cJSON * root = cJSON_CreateObject();
    if(root == NULL) {
        printf("pack_friend_apply_json: 创建根对象失败\n");
        return NULL;
    }

    cJSON_AddStringToObject(root, "type", "friend_apply_action");

    cJSON * payload = cJSON_CreateObject();
    if(payload == NULL) {
        printf("pack_friend_apply_json: 创建payload对象失败\n");
        cJSON_Delete(root);
        return NULL;
    }

    cJSON_AddNumberToObject(payload, "apply_id", apply_id);
    cJSON_AddStringToObject(payload, "action", action);

    cJSON_AddItemToObject(root, "payload", payload);

    char * json_str = cJSON_PrintUnformatted(root);
    if(json_str == NULL) {
        printf("pack_friend_apply_json: JSON转换为字符串失败\n");
        cJSON_Delete(root);
        return NULL;
    }

    cJSON_Delete(root);
    return json_str;
}

// 重新拉取好友申请列表并刷新页面
void refresh_friend_apply_list()
{
    pack_get_friend_apply_list_json_request();

    // 等待服务器响应并更新缓存
    usleep(50000);

    pthread_mutex_lock(&g_cache_mutex);

    if(g_friend_apply_overlay != NULL && lv_obj_is_valid(g_friend_apply_overlay)) {
        if(new_friend_list_card != NULL && lv_obj_is_valid(new_friend_list_card)) {
            lv_obj_clean(new_friend_list_card);
            render_friend_list_from_cache(new_friend_list_card, &g_friend_apply_cache);
        }
    }

    pthread_mutex_unlock(&g_cache_mutex);
}

// 根据申请ID删除全局缓存中的对应项（外部已加锁）
static void remove_cache_item_by_apply_id(int apply_id)
{
    if(g_friend_apply_cache.count == 0 || g_friend_apply_cache.items == NULL) {
        return;
    }

    // 1. 查找目标索引
    int target_idx = -1;
    for(int i = 0; i < g_friend_apply_cache.count; i++) {
        if(g_friend_apply_cache.items[i].apply_id == apply_id) {
            target_idx = i;
            break;
        }
    }
    if(target_idx == -1) {
        return;
    }

    // 2. 处理缓存缩小
    g_friend_apply_cache.count--;
    if(g_friend_apply_cache.count == 0) {
        free(g_friend_apply_cache.items);
        g_friend_apply_cache.items = NULL;
        g_has_new_data             = false;
    } else {
        FriendApplyItem_t * new_items = (FriendApplyItem_t *)realloc(
            g_friend_apply_cache.items, sizeof(FriendApplyItem_t) * g_friend_apply_cache.count);
        if(new_items == NULL) {
            new_items = (FriendApplyItem_t *)malloc(sizeof(FriendApplyItem_t) * g_friend_apply_cache.count);
            if(new_items == NULL) {
                printf("remove_cache_item_by_apply_id: 内存分配失败\n");
                free(g_friend_apply_cache.items);
                g_friend_apply_cache.items = NULL;
                g_friend_apply_cache.count = 0;
                g_has_new_data             = false;
                return;
            }
            memcpy(new_items, g_friend_apply_cache.items, sizeof(FriendApplyItem_t) * target_idx);
            memcpy(new_items + target_idx, g_friend_apply_cache.items + target_idx + 1,
                   sizeof(FriendApplyItem_t) * (g_friend_apply_cache.count - target_idx));
            free(g_friend_apply_cache.items);
        }
        g_friend_apply_cache.items = new_items;
    }

    g_has_new_data = (g_friend_apply_cache.count > 0);
    printf("本地缓存已删除申请ID: %d，剩余申请数: %d\n", apply_id, g_friend_apply_cache.count);
}
